/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of GW-Android.

GW-Android is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GW-Android is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GW-Android. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.android.components;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import br.ufes.cwtools.android.Component;
import br.ufes.cwtools.android.R;

public class ImagePicker extends Component {
	private static final String TAG = "ImagePicker";
	
	private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
	private static final int REQUEST_CODE_IMAGE_PICK = 2;
	
	private static final String EXTRA_IMAGE_URI = "image_uri";  // Key para passar ao componente seguinte.
	
	private File temp = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.component_image_picker);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode) {
		case REQUEST_CODE_IMAGE_CAPTURE:
			if (resultCode == RESULT_OK) {
				Log.d(TAG, "IMAGE_CAPTURE result OK.");
				
				if (temp == null) {
					Log.w(TAG, "Image capture result received, but no temp file found!");
					return;
				}
				String sUri = "";
				try {
				    sUri = MediaStore.Images.Media.insertImage(this.getContentResolver(), temp.getAbsolutePath(), null, null);
				    temp.delete();
				    temp = null;
				    this.getIntent().putExtra(EXTRA_IMAGE_URI, sUri);
				} catch (FileNotFoundException e) {
					return;
				}
				
//				Uri uri = data.getData();
//				Bitmap bm = (Bitmap) data.getExtras().get("data");  // Thumbnail.
//				String sUri = MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);  // Salva a imagem.
				
				this.getIntent().putExtra(EXTRA_IMAGE_URI, sUri);  // Passa a informação para o componente seguinte.
				this.finish();
			} else {
				Log.d(TAG, "IMAGE_CAPTURE result not OK.");
			}
			break;
		case REQUEST_CODE_IMAGE_PICK:
			if (resultCode == RESULT_OK) {
				Log.d(TAG, "IMAGE_PICK_REQUEST result OK.");
				Uri uri = data.getData();
				String sUri = uri.toString();
				this.getIntent().putExtra(EXTRA_IMAGE_URI, sUri);
				this.finish();
			} else {
				Log.d(TAG, "IMAGE_PICK_REQUEST result not OK.");
			}
			break;
		default:
			Log.w(TAG, "Activity returned with unknown request code.");
			break;
		}
	}
	
	public void imageCaptureOnClick(View view) {
		Log.d(TAG, "Launching image capture activity.");
		
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file;
		try {
			file = File.createTempFile("temp_file", "jpg");
		} catch (IOException e) {
			return;
		}
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		this.temp = file;
		this.startActivityForResult(intent, REQUEST_CODE_IMAGE_CAPTURE);
		
//		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//		intent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		
		// TODO Tratar erro quando não existe uma activity para executar esta ação;
		// duas opções: verificar previamente e desabilitar o botão ou capturar a exceção no startActivity.
	}
	
	public void galleryOnClick(View view) {
		Log.d(TAG, "Launching image pick activity.");
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		this.startActivityForResult(intent, REQUEST_CODE_IMAGE_PICK);
		// TODO Tratar erro quando não existe uma activity para executar esta ação.
	}
}
